package com.px.gateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.pre.PreDecorationFilter;
import org.springframework.stereotype.Component;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.*;

/**
 * change swagger basePath from /v2/api-docs,
 * refer to {@link PreDecorationFilter#addProxyPrefix} and {@link X_FORWARDED_PREFIX_HEADER}
 */
@Component
public class SwaggerHeaderFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return ROUTE_TYPE;
    }

    @Override
    public int filterOrder() {
        return PRE_DECORATION_FILTER_ORDER + 1;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        String prefix = ctx.getZuulRequestHeaders().get(X_FORWARDED_PREFIX_HEADER.toLowerCase());
        return prefix != null;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        String prefix = ctx.getZuulRequestHeaders().get(X_FORWARDED_PREFIX_HEADER.toLowerCase());
        if (!prefix.endsWith("/api"))
            ctx.addZuulRequestHeader(X_FORWARDED_PREFIX_HEADER, prefix + "/api");
        return null;
    }
}
